#include "drvs.h"
#include "regs.h"
#include "adpcm.h"
#include "string.h"
#include "sadc.h"

static void adc_calibration(void)
{
    uint8_t aux_flag = 0;
    
    // enable adc.
    SADC->SADC_ANA_CTRL.SADC_EN   = 1;
    
    // clear last flag.
    SADC->STCTRL.SADC_AUX_FLG_CLR = 1;
    
    // enable calibration mode.
    SADC->CTRL.SADC_CALIB_MODE    = 1;
    
    // start calibration.
    SADC->CTRL.SADC_SOC = 1;
    
    do 
    {
        // start calibration.
//        SADC->CTRL.SADC_SOC = 1;
        
        // wait aux_flag is 1.
        aux_flag = SADC->STCTRL.SADC_AUX_FLG;
    } while (!aux_flag);
    
    // clear calibration done flag.
    SADC->STCTRL.SADC_AUX_FLG_CLR = 1;
    
    for (uint8_t i = 0; i < 16; i++)
    {
        SADC->SADC_CALIB_DATSEL = i;
    }
    
    // disable calibration mode.
    SADC->CTRL.SADC_CALIB_MODE    = 0;
    
    // stop calibration.
    SADC->CTRL.SADC_SOC = 0;
}

void adc_mic_init(void)
{
    RCC->AHBCLK_EN_RUN.ADC_CLKEN_RUN = 0;
    RCC->AHBRST_CTRL.ADC_RSTREQ      = 1;
    RCC->AHBRST_CTRL.ADC_RSTREQ      = 0;
    RCC->AHBCLK_EN_RUN.ADC_CLKEN_RUN = 1;
    
    SADC->CTRL.SADC_CLK_PH      = ADC_CLK_CONV_AT_POSEDGE; //ADC_CLK_CONV_AT_NEGEDGE;
     
    // 0, VBG; 1, VDD
    SADC->SADC_ANA_CTRL.SADC_VREF_SEL = 0;
    
    // bias voltage adjust
    SADC->MIC_CTRL.MIC_MODE_SEL = 0;
    SADC->MIC_CTRL.MIC_VREF_SEL = 1;
    // mic power enable
    SADC->MIC_CTRL.MIC_PD = 0;
    
    SADC->MIC_CTRL.PGA_BIAS_SEL = 1;
    // gain 39dB
    //SADC->MIC_CTRL.PGA_VOL = 0;
    // pga enable
    SADC->MIC_CTRL.PGA_EN = 1;    
    
    adc_calibration();
    
    SADC->CTRL.SADC_SAMP_MOD    = ADC_SAMPLE_MODE_FILTER; //ADC_SAMPLE_MODE_NORMAL; //;ADC_SAMPLE_MODE_ADTMR_TRIG
    
    SADC->DC_OFFSET = 0x200;
    
    SADC->CTRL.SADC_HPF_COEF = 3;
    
    SADC->CTRL.SADC_AUX_CLK_DIV = 0; 
    SADC->CTRL.SADC_CONV_MODE = 0;  
    
}
